package com.example.test_witns.ui.todo;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.NavOptions;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.test_witns.R;
import com.example.test_witns.adapter.todoAdapter.TodoAdapter;
import com.example.test_witns.databinding.FragmentTodoBinding;
import com.example.test_witns.pojo.TaskListResponse;
import com.example.test_witns.pojo.TaskResponse;
import com.example.test_witns.pojo.TodoTask;
import com.example.test_witns.ui.devices.DevicesViewModel;
import com.example.test_witns.ui.sheets.AddTaskBottomSheet;
import com.example.test_witns.ui.sheets.ModifyTaskBottomSheet;
import com.example.test_witns.ui.sheets.TaskBottomSheet;
import com.example.test_witns.utils.MyInfosHelper;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;

public class TodoFragment extends Fragment implements AddTaskBottomSheet.OnTaskCreatedListener, ModifyTaskBottomSheet.OnTaskModifiedListener {
    private FragmentTodoBinding binding;
    private RecyclerView recyclerView;
    private TodoAdapter adapter;
    private TextView todo_all_done;
    private TextView tv_progress;
    CopyOnWriteArrayList<TodoTask> taskList;
    private ImageView all_done_image_view;
    private Button btn_clean;
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    public static int finishedTask = 0;
    private MyInfosHelper myInfosHelper;
    private TextView todo_toolbar;

    public interface TaskApiService {
        @POST("/saveTask")
        Call<TaskResponse> saveTask(@Body TodoTask task);

        @DELETE("/deleteTask")
        Call<TaskResponse> deleteTaskById(@Query("id") Long id);

        @PUT("/updateTask")
        Call<TaskResponse> updateTask(@Body TodoTask task);

        @GET("/getTaskById")
        Call<TaskResponse> getTaskById(@Query("id") Long id);

        @GET("/getTasksByUserEmail")
        Call<TaskListResponse> getTasksByUserEmail(@Query("userEmail") String userEmail);

        @PUT("/complete/{id}")
        Call<TaskListResponse> updateCompleteStatusById(@Path("id") Long taskId, @Query("isCompleted") boolean isCompleted);
    }

    public interface LoadTasksCallback{
        void OnSuccess(int loadedTasksNum);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        DevicesViewModel devicesViewModel =
                new ViewModelProvider(this).get(DevicesViewModel.class);

        binding = FragmentTodoBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        finishedTask = 0;

        myInfosHelper = new MyInfosHelper(getContext());

        all_done_image_view = root.findViewById(R.id.all_done_image_view);

        todo_toolbar = root.findViewById(R.id.todo_toolbar);
        recyclerView = root.findViewById(R.id.rv_tasks);
        taskList = new CopyOnWriteArrayList<>();
        adapter = new TodoAdapter(taskList, getContext());
        adapter.setRecyclerView(recyclerView);

        adapter.setOnTaskClickListener(new TodoAdapter.OnTaskClickListener() {
            @Override
            public void OnTaskClicked(TodoTask task, TaskBottomSheet bottomSheet) {
                bottomSheet.show(getParentFragmentManager(), bottomSheet.getTag());
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);

        FloatingActionButton fabAdd = root.findViewById(R.id.fab_add);
        fabAdd.setOnClickListener(v -> showAddTaskDialog());

        setupItemTouchHelper();

        Window window = requireActivity().getWindow();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        window.setStatusBarColor(Color.parseColor("#FEF7FF"));

        NavOptions navOptions = new NavOptions.Builder()
                .setLaunchSingleTop(false) // 确保如果目标 Fragment 已经在顶部，不会创建新的实例
                .setPopUpTo(R.id.navigation_home, true) // 设置为 true 将移除直到起始目的地的所有 Fragment
                .setRestoreState(false) // 不恢复状态，通常与 setPopUpTo 结合使用
                .build();

        NavController navController = NavHostFragment.findNavController(this);

        TextView textView_analysis = root.findViewById(R.id.Home_analysis);
        textView_analysis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navController.navigate(R.id.action_navigation_todo_to_navigation_analysis,null, navOptions);
                onDestroyView();
            }
        });

        TextView textView_recommendation = root.findViewById(R.id.Home_recommendation);
        textView_recommendation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                navController.navigate(R.id.action_navigation_todo_to_navigation_home,null, navOptions);
            }
        });

        tv_progress = root.findViewById(R.id.tv_progress);
        String tv_progressString = "已完成 " + finishedTask + "/" + taskList.size() +" 项";
        tv_progress.setText(tv_progressString);

        todo_all_done = root.findViewById(R.id.todo_all_done);
        if (taskList.isEmpty()){
            todo_all_done.setVisibility(View.VISIBLE);
            all_done_image_view.setVisibility(View.VISIBLE);
        }
        adapter.setTodoAllDoneTextView(todo_all_done);
        adapter.setTodoAllDoneImageView(all_done_image_view);
        adapter.setTv_progressTextView(tv_progress);
        adapter.setOnItemModifiedListener(new TodoAdapter.OnItemModifiedListener() {
            @Override
            public void onItemModified(TodoTask initialTask, TodoTask modifiedTask) {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + "101.35.251.218" + ":8080/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                TaskApiService taskApiService = retrofit.create(TaskApiService.class);
                initialTask.setOwnerUserEmail(myInfosHelper.getMyUserId());
                Call<TaskResponse> call = taskApiService.updateTask(initialTask);
                call.enqueue(new Callback<TaskResponse>() {
                    @Override
                    public void onResponse(Call<TaskResponse> call, Response<TaskResponse> response) {
                        for (TodoTask task : taskList){
                            if (task.getId() == initialTask.getId()){
                                adapter.modifyTask(task, modifiedTask);
                                showToastAboveView(todo_toolbar, getContext(), "任务更新成功");
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<TaskResponse> call, Throwable t) {

                    }
                });
            }
        });

        adapter.setOnItemDeletedListener(new TodoAdapter.OnItemDeletedListener() {
            @Override
            public void onItemDeleted(TodoTask DeletedTask) {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + "101.35.251.218" + ":8080/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                TaskApiService taskApiService = retrofit.create(TaskApiService.class);
                Call<TaskResponse> call = taskApiService.deleteTaskById(DeletedTask.getId());
                call.enqueue(new Callback<TaskResponse>() {
                    @Override
                    public void onResponse(Call<TaskResponse> call, Response<TaskResponse> response) {
                        for (TodoTask todoTask : taskList){
                            if (todoTask.getId() == DeletedTask.getId()){
                                int position = taskList.indexOf(todoTask);
                                showUndoSnackbar(position); // 显示撤销删除的 Snackbar
                                if (taskList.get(position).isCompleted()){
                                    finishedTask--;
                                }
                                taskList.remove(position); // 从数据源中移除
                                adapter.notifyItemRemoved(position); // 通知 RecyclerView 更新
                                String tv_progressString = "已完成 " + finishedTask + "/" + taskList.size() +" 项";
                                tv_progress.setText(tv_progressString);
                                if (taskList.isEmpty()){
                                    todo_all_done.setVisibility(View.VISIBLE);
                                    all_done_image_view.setVisibility(View.VISIBLE);
                                }
                                showToastAboveView(todo_toolbar, getContext(), "删除任务成功");
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<TaskResponse> call, Throwable t) {

                    }
                });
            }
        });

        adapter.setOnCompleteStatusChangedListener(new TodoAdapter.OnCompleteStatusChangedListener() {
            @Override
            public void onCompleted(long id) {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + "101.35.251.218" + ":8080/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                TaskApiService taskApiService = retrofit.create(TaskApiService.class);
                Call<TaskListResponse> call = taskApiService.updateCompleteStatusById(id, true);
                call.enqueue(new Callback<TaskListResponse>() {
                    @Override
                    public void onResponse(Call<TaskListResponse> call, Response<TaskListResponse> response) {
                        showToastAboveView(todo_toolbar, getContext(), "完成");
                    }

                    @Override
                    public void onFailure(Call<TaskListResponse> call, Throwable t) {
                        showToastProhibitedStyleAboveView(todo_toolbar, getContext(), "服务器同步失败, 请检查网络");
                    }
                });
            }

            @Override
            public void onUncompleted(long id) {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + "101.35.251.218" + ":8080/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                TaskApiService taskApiService = retrofit.create(TaskApiService.class);
                Call<TaskListResponse> call = taskApiService.updateCompleteStatusById(id, false);
                call.enqueue(new Callback<TaskListResponse>() {
                    @Override
                    public void onResponse(Call<TaskListResponse> call, Response<TaskListResponse> response) {
                        showToastAboveView(todo_toolbar, getContext(), "取消");
                    }

                    @Override
                    public void onFailure(Call<TaskListResponse> call, Throwable t) {
                        showToastProhibitedStyleAboveView(todo_toolbar, getContext(), "服务器同步失败, 请检查网络");
                    }
                });
            }
        });

        btn_clean = root.findViewById(R.id.btn_clean);
        btn_clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (TodoTask todoTask : taskList){
                    if (todoTask.isCompleted()){
                        int position = taskList.indexOf(todoTask);
                        deleteTask(position, todoTask);
                    }
                }
            }
        });

        loadTasks(new LoadTasksCallback() {
            @Override
            public void OnSuccess(int loadedTasksNum) {
                if (!taskList.isEmpty()){
                    todo_all_done.setVisibility(View.INVISIBLE);
                    all_done_image_view.setVisibility(View.INVISIBLE);
                }
            }
        });

        SwipeRefreshLayout swipeRefreshLayout = root.findViewById(R.id.swipeRefreshLayout_todo);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.removeAll();
                        refreshTasks(new LoadTasksCallback() {
                            @Override
                            public void OnSuccess(int loadedTasksNum) {
                                swipeRefreshLayout.setRefreshing(false); // 刷新完成后关闭刷新动画
                                String message = "任务刷新成功";
                                showToastAboveView(todo_toolbar, getContext(), message);
                            }
                        });
                    }
                }).start();
            }
        });

        return root;
    }

    private void loadTasks(LoadTasksCallback loadTasksCallback) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://" + "101.35.251.218" + ":8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        TaskApiService taskApiService = retrofit.create(TaskApiService.class);
        Call<TaskListResponse> call = taskApiService.getTasksByUserEmail(myInfosHelper.getMyUserId());
        call.enqueue(new Callback<TaskListResponse>() {
            @Override
            public void onResponse(Call<TaskListResponse> call, Response<TaskListResponse> response) {
                List<TodoTask> todoTaskList = response.body().getData();
                for (TodoTask task : todoTaskList){
                    String[] dueTimeArr = task.getDueTime().split(":");
                    task.setDueTime(dueTimeArr[0] + ":" +dueTimeArr[1]);
                    adapter.addTask(task);
                    if (task.isCompleted()){
                        finishedTask++;
                    }
                }
                String tv_progressString = "已完成 " + finishedTask + "/" + taskList.size() +" 项";
                tv_progress.setText(tv_progressString);
                loadTasksCallback.OnSuccess(finishedTask);
            }

            @Override
            public void onFailure(Call<TaskListResponse> call, Throwable t) {
                showToastProhibitedStyleAboveView(todo_toolbar, getContext(), "获取任务列表失败");
            }
        });
    }

    private void refreshTasks(LoadTasksCallback loadTasksCallback){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://" + "101.35.251.218" + ":8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        TaskApiService taskApiService = retrofit.create(TaskApiService.class);
        Call<TaskListResponse> call = taskApiService.getTasksByUserEmail(myInfosHelper.getMyUserId());
        call.enqueue(new Callback<TaskListResponse>() {
            @Override
            public void onResponse(Call<TaskListResponse> call, Response<TaskListResponse> response) {
                List<TodoTask> todoTaskList = response.body().getData();
                for (TodoTask task : todoTaskList){
                    String[] dueTimeArr = task.getDueTime().split(":");
                    task.setDueTime(dueTimeArr[0] + ":" +dueTimeArr[1]);
                    adapter.addTask(task);
                }
                String tv_progressString = "已完成 " + finishedTask + "/" + taskList.size() +" 项";
                tv_progress.setText(tv_progressString);
                loadTasksCallback.OnSuccess(finishedTask);
            }

            @Override
            public void onFailure(Call<TaskListResponse> call, Throwable t) {

            }
        });
    }

    private void setupItemTouchHelper() {
        ItemTouchHelper.SimpleCallback touchHelperCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                deleteTask(position, null);
            }
        };

        new ItemTouchHelper(touchHelperCallback).attachToRecyclerView(recyclerView);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void showAddTaskDialog() {
        // 显示底部弹窗
        AddTaskBottomSheet bottomSheet = new AddTaskBottomSheet();
        bottomSheet.setOnTaskCreatedListener(this);
        bottomSheet.show(getActivity().getSupportFragmentManager(), bottomSheet.getTag());
    }

    private void deleteTask(int position, TodoTask targetTask) {
        if (targetTask != null){
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://" + "101.35.251.218" + ":8080/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            TaskApiService taskApiService = retrofit.create(TaskApiService.class);
            Call<TaskResponse> call = taskApiService.deleteTaskById(targetTask.getId());
            call.enqueue(new Callback<TaskResponse>() {
                @Override
                public void onResponse(Call<TaskResponse> call, Response<TaskResponse> response) {
                    int targetPosition = taskList.indexOf(targetTask);
                    showUndoSnackbar(targetPosition); // 显示撤销删除的 Snackbar
                    if (taskList.get(targetPosition).isCompleted()){
                        finishedTask--;
                    }
                    taskList.remove(targetPosition); // 从数据源中移除
                    adapter.notifyItemRemoved(targetPosition); // 通知 RecyclerView 更新
                    String tv_progressString = "已完成 " + finishedTask + "/" + taskList.size() +" 项";
                    tv_progress.setText(tv_progressString);
                    if (taskList.isEmpty()){
                        todo_all_done.setVisibility(View.VISIBLE);
                        all_done_image_view.setVisibility(View.VISIBLE);
                    }
                    showToastAboveView(todo_toolbar, getContext(), "删除任务成功");
                }

                @Override
                public void onFailure(Call<TaskResponse> call, Throwable t) {

                }
            });
        }else {
            TodoTask task = taskList.get(position);
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://" + "101.35.251.218" + ":8080/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            TaskApiService taskApiService = retrofit.create(TaskApiService.class);
            Call<TaskResponse> call = taskApiService.deleteTaskById(task.getId());
            call.enqueue(new Callback<TaskResponse>() {
                @Override
                public void onResponse(Call<TaskResponse> call, Response<TaskResponse> response) {
                    showUndoSnackbar(position); // 显示撤销删除的 Snackbar
                    if (taskList.get(position).isCompleted()){
                        finishedTask--;
                    }
                    taskList.remove(position); // 从数据源中移除
                    adapter.notifyItemRemoved(position); // 通知 RecyclerView 更新
                    String tv_progressString = "已完成 " + finishedTask + "/" + taskList.size() +" 项";
                    tv_progress.setText(tv_progressString);
                    if (taskList.isEmpty()){
                        todo_all_done.setVisibility(View.VISIBLE);
                        all_done_image_view.setVisibility(View.VISIBLE);
                    }
                    showToastAboveView(todo_toolbar, getContext(), "删除任务成功");
                }

                @Override
                public void onFailure(Call<TaskResponse> call, Throwable t) {

                }
            });
        }

    }

    private void showUndoSnackbar(int position) {
        TodoTask deletedTask = taskList.get(position);
        Snackbar snackbar = Snackbar.make(recyclerView, deletedTask.getTitle() + " 任务已删除", Snackbar.LENGTH_LONG);
        snackbar.setAction("撤销", v -> {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://" + "101.35.251.218" + ":8080/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            TaskApiService taskApiService = retrofit.create(TaskApiService.class);
            deletedTask.setOwnerUserEmail(myInfosHelper.getMyUserId());
            Call<TaskResponse> call = taskApiService.saveTask(deletedTask);
            call.enqueue(new Callback<TaskResponse>() {
                @Override
                public void onResponse(Call<TaskResponse> call, Response<TaskResponse> response) {
                    if (response.body() != null && response.body().getStatus() == 1) {
                        deletedTask.setId(response.body().getData().getId());
                        taskList.add(position, deletedTask);
                        adapter.notifyItemInserted(position);
                        todo_all_done.setVisibility(View.INVISIBLE);
                        all_done_image_view.setVisibility(View.INVISIBLE);
                        if (deletedTask.isCompleted()){
                            finishedTask++;
                        }
                        String tv_progressString = "已完成 " + finishedTask + "/" + taskList.size() +" 项";
                        tv_progress.setText(tv_progressString);

                        showToastAboveView(todo_toolbar, getContext(), "撤销成功");
                    }
                }

                @Override
                public void onFailure(Call<TaskResponse> call, Throwable t) {
                    showToastProhibitedStyleAboveView(todo_toolbar, getContext(), "撤销失败");
                }
            });
        });
        snackbar.show();
    }


    /**
     * @param task
     */
    @Override
    public void onTaskCreated(TodoTask task) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://" + "101.35.251.218" + ":8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        TaskApiService taskApiService = retrofit.create(TaskApiService.class);
        task.setOwnerUserEmail(myInfosHelper.getMyUserId());
        Call<TaskResponse> call = taskApiService.saveTask(task);
        call.enqueue(new Callback<TaskResponse>() {
            @Override
            public void onResponse(Call<TaskResponse> call, Response<TaskResponse> response) {
                if (response.body() != null && response.body().getStatus() == 1) {
                    task.setId(response.body().getData().getId());
                    Toast.makeText(getContext(), String.valueOf(response.body().getData().getOwnerUserEmail()), Toast.LENGTH_SHORT).show();
                    adapter.addTask(task);
                    recyclerView.smoothScrollToPosition(taskList.size() - 1); // 滚动到新任务
                    todo_all_done.setVisibility(View.INVISIBLE);
                    all_done_image_view.setVisibility(View.INVISIBLE);
                    if (task.isCompleted()) {
                        finishedTask++;
                    }
                    String tv_progressString = "已完成 " + finishedTask + "/" + taskList.size() + " 项";
                    tv_progress.setText(tv_progressString);

                    showToastAboveView(todo_toolbar, getContext(), "任务添加成功");
                }
            }

            @Override
            public void onFailure(Call<TaskResponse> call, Throwable t) {
                showToastProhibitedStyleAboveView(todo_toolbar, getContext(), "任务创建失败");
            }
        });
    }

    @Override
    public void onTaskModified(TodoTask initialTask, TodoTask modifiedTask) {

    }

    public void showToastAboveView(View view, Context context, String message) {
        // 创建Toast
        View customView = LayoutInflater.from(context).inflate(R.layout.custom_toast_confirm_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(context);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 获取控件的位置（相对于屏幕）
        int[] location = new int[2];
        view.getLocationOnScreen(location); // 获取控件在屏幕上的位置
        int viewX = location[0]; // 控件的X坐标
        int viewY = location[1]; // 控件的Y坐标

        WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = 0;
        if (insets != null) {
            cutoutHeight = insets.getSystemWindowInsetTop(); // 获取刘海高度
        }

        // 计算Toast的偏移量
        int xOffset = 0; // 水平偏移量，与控件的X坐标对齐
        int yOffset = viewY - cutoutHeight; // 垂直偏移量，让Toast显示在控件的顶部

        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, xOffset, yOffset);

        // 显示Toast
        toast.show();
    }

    public void showToastProhibitedStyleAboveView(View view, Context context, String message) {
        // 创建Toast
        View customView = LayoutInflater.from(context).inflate(R.layout.custom_toast_prohibited_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(context);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 获取控件的位置（相对于屏幕）
        int[] location = new int[2];
        view.getLocationOnScreen(location); // 获取控件在屏幕上的位置
        int viewX = location[0]; // 控件的X坐标
        int viewY = location[1]; // 控件的Y坐标

        WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = 0;
        if (insets != null) {
            cutoutHeight = insets.getSystemWindowInsetTop(); // 获取刘海高度
        }

        // 计算Toast的偏移量
        int xOffset = 0; // 水平偏移量，与控件的X坐标对齐
        int yOffset = viewY - cutoutHeight; // 垂直偏移量，让Toast显示在控件的顶部

        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, xOffset, yOffset);

        // 显示Toast
        toast.show();
    }
}
